
var createNewController = null;
var createNewActivityConstants = {"$domEltObj":null};
(function(doc, win) {
	
 
    
    // sui 页面就绪时间
    $(doc).on("pageInit", "#createNewActivityPage", function(e, pageId, $page,isBack) {
    	closePageWindow("createNewActivityPage");
        var paramObj = CommonUtil.takeOutParamObject();
        if(paramObj && paramObj.createActivityParams!=undefined){
        	createActivityPublicParam = paramObj.createActivityParams;
        }
        if(paramObj && paramObj.reload!=undefined && !paramObj.reload){//防止刷新页面;
        	if(createActivityPublicParam.activityType == ACTIVITY_TYPE.ITEM_MARKET.val || createActivityPublicParam.activityType==ACTIVITY_TYPE.LATTER_SEND.val){
             	if(createActivityPublicParam.isRelativeTime == true){
            		$("#createNewActivityPage .label-switch").find("input").removeAttr("disabled");
            	}else{
            		$("#createNewActivityPage #auto_continue").prop("checked",false);
            		$("#createNewActivityPage .label-switch").find("input").attr("disabled","disabled");
            	}
        	}
        	return;
        }  
    	if(isBack){
    		 if(paramObj && paramObj!=null){
    			  $.extend(createActivityPublicParam.otherSetting,paramObj);
    		 }    
			 return;
		}
    	createNewController = new CreateNewController();
		ActivityPreloadData.loadDataTimer({
					"func0" : function() {
						var paramObj = CommonUtil.takeOutParamObject();
						if(paramObj.activityType != ACTIVITY_TYPE.ITEM_MARKET.val){
							ActivityPreloadData.createPrerequisite();
						}else{
							ActivityPreloadData.executeFuncTimes--;
						}			
					},
					"func1" : function(){
						ActivityPreloadData.checkSupplierIsSignedKouBeiKe();
					},
					"func2":  function(){
						ActivityPreloadData.getKouBeiKeConfigInfo();
					},
					"func3" : function(){
						ActivityPreloadData.loadUserServiceInfo();
					},
					"callBackEvent" : function() {
				
						createNewController.initPageData();
					}
	            });
    	  	
    });
    
    
    /**
     * 编辑优惠券弹窗;
     */
    $(doc).on("click", "#createNewActivityPage .quan", function() {
    	 showPageWindow("createNewActivityPage","discountQuan");
    	 createNewController.saveActivityData();
    	 createNewController.initEditVoucherPageData();
    	 createNewController.bindVoucherTimeWidget();
    });
    
    /**
     * 取消事件;
     */
    $(doc).on("click", "#createNewActivityPage .dailog-form .cancel,.dailog-form .layer-overlay", function() {
    	 closePageWindow("createNewActivityPage");
    	 var id = $(this).attr("id"); 	 
    	 if(id == "zfb-cancel"){	
    		if(createActivityPublicParam.voucherSloganLocalOldFilePath!=""){
    			createActivityPublicParam.voucherSloganLocalFilePath =createActivityPublicParam.voucherSloganLocalOldFilePath; 
    		}else{
    			createActivityPublicParam.voucherSloganLocalFilePath = "";
    		}
    		createActivityPublicParam.voucherSloganNewUri = createActivityPublicParam.voucherSloganUri;//还原为选择上传前的图片url;
    		createActivityPublicParam.voucherSloganNewId  = createActivityPublicParam.voucherSloganUrlId;//还原为选择上传前的图片id;
 	 
    	 }else if(id =="editVoucherCancel"){
    		createNewController.bindActivityTimeWidget();//这里需要重新绑定活动时间联动控件
    	 } 
     
    });
    
    
    
    
    /**
     * 确定事件;
     */
    $(doc).on("click", "#createNewActivityPage .dailog-form .sure", function() {    	
    	 var id = $(this).attr("id"); 	 
    	 if(id == "zfb-sure"){	
    		  closePageWindow("createNewActivityPage");
              createNewController.saveZfbData();
    	 }else if(id =="editVoucherSure"){
    		 if(createNewController.checkVoucherData()==true){
    			  closePageWindow("createNewActivityPage");
        		  createNewController.saveVoucherData();
        	      createNewController.bindActivityTimeWidget();	
        	      createNewController.renderHtmlData();
    		 }	
    	 }else if(id =="kbk_sure"){
    		  if(createNewController.checkKbKData()==true){
    	    	   createNewController.saveCommissionData();
    	    	   closePageWindow("createNewActivityPage");
    	           if(createNewActivityConstants.$domEltObj!=null){
    	        	  if(createActivityPublicParam.isOpenKbk == true){
    	        		  createNewActivityConstants.$domEltObj.addClass("checked");
    	        	  }else{
    	        		  createNewActivityConstants.$domEltObj.removeClass("checked"); 
    	        	  }
    	             
    	           } 
    	      }   	
    	 }
     
    });
    
 
    
    
    
    /**
     * 商品图片上传事件;
     */
    $(doc).on("click","#createNewActivityPage #discountPic",function(){
    	$.actions([[{
			"text" : "相册",
			"onClick" : function(){
				   AppUtil.call(AppUtil.APIS.SELECT_PICTURE,{"compress":{"sizeLimit":"500","unit":"K"},"crop":{"heightRatio":"1","widthRatio":"1"},"format":"JPG","maxNum":"1"},
			                function(selectResult){
			                	if(selectResult.success.toString() == "true"){
			                		if(selectResult.resultObject && selectResult.resultObject instanceof Array){
			                			createActivityPublicParam.voucherSloganLocalFilePath = selectResult.resultObject[0];
			                			common.loading("图片上传中...");
			                			AppUtil.call(AppUtil.APIS.UPLOAD_PICTURE,
			                	                {
			                				       "file":createActivityPublicParam.voucherSloganLocalFilePath,
			                				       "url":App.serverUrl + "app/img/uploadActivityImg.do"
			                	                },
			                	                function(uploadResult){
			                	                	if(uploadResult.success.toString() == "true" && uploadResult.resultObject.success.toString() == "true"){
			                	                		if(uploadResult.resultObject && uploadResult.resultObject != null){
			                	                			createActivityPublicParam.voucherSloganNewUri = App.previewUrlPrefix + uploadResult.resultObject.resultObject.imageUrl;
			                	                			createActivityPublicParam.voucherSloganNewId = uploadResult.resultObject.resultObject.imageId;
			                	                			createActivityPublicParam.voucherSlogan = $("#createNewActivityPage #discountDoc").val();
			                	                			createNewController.initZfbPageData();
			                	                		}else{
			                	                			DialogUtil.dialogWarn("未正确返回优惠图片上传结果!");            			
			                	                		}
			                	                	         		
			                	                	}else if(result.code == -1){
			                	                		  DialogUtil.dialogWarn(uploadResult.msg);         		 
			                	                	} 
			                	                	common.closeLoading();
			                	            });
			                			
			                		
			                		}
			                	         		
			                	}else {
			                		  DialogUtil.dialogWarn("选择优惠图片异常!"+selectResult.msg);
			                		  return;
			                	}                 
			            });
			}
		},{
			"text" : "拍照",
			"onClick" : function(){			
				 AppUtil.call(AppUtil.APIS.TAKE_PICTURE,{"compress":{"sizeLimit":"500","unit":"K"},"crop":{"heightRatio":"1","widthRatio":"1"},"format":"JPG","maxNum":"1"},
			                function(selectResult){
			                	if(selectResult.success.toString() == "true"){
			                		if(selectResult.resultObject && selectResult.resultObject!=""){
			                			createActivityPublicParam.voucherSloganLocalFilePath = selectResult.resultObject;   		    
			                			common.loading("图片上传中...");
			                			AppUtil.call(AppUtil.APIS.UPLOAD_PICTURE,
			                	                {
			                				       "file":createActivityPublicParam.voucherSloganLocalFilePath,
			                				       "url":App.serverUrl + "app/img/uploadActivityImg.do"
			                	                },
			                	                function(uploadResult){
			                	                	if(uploadResult.success.toString() == "true" && uploadResult.resultObject.success.toString() == "true"){
			                	                		if(uploadResult.resultObject && uploadResult.resultObject != null){
			                	                			createActivityPublicParam.voucherSloganNewUri = App.previewUrlPrefix + uploadResult.resultObject.resultObject.imageUrl;
			                	                			createActivityPublicParam.voucherSloganNewId = uploadResult.resultObject.resultObject.imageId;  
			                	                			createActivityPublicParam.voucherSlogan = $("#createNewActivityPage #discountDoc").val();
			                	                			createNewController.initZfbPageData();
			                	                		}else{
			                	                			DialogUtil.dialogWarn("未正确返回优惠图片上传结果!");            			
			                	                		}
			                	                	         		
			                	                	}else if(result.code == -1){
			                	                		  DialogUtil.dialogWarn(uploadResult.msg);         		 
			                	                	} 
			                	                	common.closeLoading();
			                	            });
			                			
			                		
			                		}
			                	         		
			                	}else{
			                		  DialogUtil.dialogWarn("选择图片异常!"+selectResult.msg);
			                		  return;
			                	}                 
			            });
				
		    }			
		}],[{
			"text" : "取消",
			"color" : "danger",
			"onClick" : function(){
			}
		}]]);
     	
    });
    

    

    /**
     * 返回事件;
     */
    $(doc).on("click","#createNewActivityPage .back",function(){
     	 if(createActivityPublicParam.activityType != ACTIVITY_TYPE.ITEM_MARKET.val && createActivityPublicParam.activityType!=ACTIVITY_TYPE.LATTER_SEND.val){
       	    ActivityPreloadData.clearCreateActivityParam();
    	 }else{
    		createNewController.saveActivityData();
    		var params = {"isFristRoute":false,"createActivityParams":createActivityPublicParam};
    		CommonUtil.injectParamObject(params);	
    	 }
     	 
    	
    });
     
    /**
     * 渠道弹窗click事件;
     * 
     */
    $(doc).on("click", "#createNewActivityPage .qudao-item>ul>li", function() {
    	  createNewActivityConstants.$domEltObj = $(this);
    	  var $channelDivClass = $(this).find("div").attr("class");    	 
    	  if($channelDivClass=="qd-icon kbk"){
    		  if(createActivityPublicParam.signedKbk==false){
    			  common.confirm({
						btnLeft : "知道了",
						title : "",
						content : "若要使用口碑客，请前去口碑商家进行签约，或咨询客服400-696-9619.",
						callbackLeft : function() {
						    return;
						} 
					});
    			 
    		  }else{
    			  //口碑客弹起;  		 
                  showPageWindow("createNewActivityPage","df-koubeike");
                  createNewController.initCommissionPageData();                  
    		  }
    	
    	  }else if($channelDivClass == "qd-icon zfb"){
    		     //支付宝弹起;
	             showPageWindow("createNewActivityPage","alipay");
	             createNewController.initZfbPageData(); 
    	  }else {
    		  if($(this).attr("class")=="checked"){
    			  $(this).removeClass("checked")	
    		  }else{
    			  $(this).addClass("checked")	
    		  }	 	     
    	  }
    	 
    });
    
    /**
     * 选择代金券有效日期类型;
     */
    $(doc).on("click", "#createNewActivityPage #quan-deadline.switch-label", function() {
    	if($("#createNewActivityPage .actions-modal-button").size()>0){
			//应该关闭模态窗口(具体怎么关由伟胜提供方法)
			$.closeModal($("#createNewActivityPage .actions-modal"));
		}
    	 var _text = $(this).children("span");
         var _self = $(this);
         var buttons1 = [
             {
                 text: '相对时间',
                 onClick: function () {
                     _text.text("相对时间");
                     _self.siblings("p").hide().eq(0).show();
                 }
             },
             {
                 text: '指定时间',
                 onClick: function () {
                	 if($("#auto_continue").attr("checked")==true){
							common.confirm({
								"title":"",
								"content": "选择指定时间，将会关闭自动续期功能，确定要选择指定时间吗?",
								"btnRight": "确定",
								"btnLeft": "取消",
								 callbackLeft: function () {//取消
									return false;
								},
								 callbackRight: function () {//确定
									_text.text("指定时间");
									_self.siblings("p").hide().eq(1).show();
									createActivityPublicParam.autoDelayFlag = 'N';//关闭自动续期;		
									return false;
								}
				           });
                	 }else{       		 
                         _text.text("指定时间");
                         _self.siblings("p").hide().eq(1).show(); 
                	 }
                	
                 }
             }
         ];
         var buttons2 = [
             {
                 text: '取消',
             }
         ];
         var groups = [buttons1, buttons2];
         $.actions(groups);
    });
    
    
    /**
     * 设置分佣金比率和上限选择事件;
     */
    $(doc).on("click", "#createNewActivityPage #commission-deadline.switch-label", function() {
    
    	if($("#createNewActivityPage .actions-modal-button").size()>0){
			//应该关闭模态窗口(具体怎么关由伟胜提供方法)
			$.closeModal($("#createNewActivityPage .actions-modal"));
		}
    	if(createActivityPublicParam.isOpenKbk==false){
    		return;
    	}
    	 var _text = $(this).children("span");
         var _self = $(this);
         var buttons1 = [
             {
                 text: '不限制',
                 onClick: function () {
                     _text.text("不限制");
                     _self.siblings("p").hide();
                     createActivityPublicParam.commissionSettingCheck == "0";
                     $("#createNewActivityPage #commissionLimit").val("");
                 }
             },
             {
                 text: '限制',
                 onClick: function () {
                     _text.text("限制");
                     _self.siblings("p").show();
                     createActivityPublicParam.commissionSettingCheck == "1";
                 }
             }
         ];
         var buttons2 = [
             {
                 text: '取消',
             }
         ];
         var groups = [buttons1, buttons2];
         $.actions(groups);
      });
    
    /**
     *  扫码送券,二维码类型选择事件;
     */
    $(doc).on("click", "#createNewActivityPage #scancode-deadline.switch-label", function() {
    	if($("#createNewActivityPage .actions-modal-button").size()>0){
			//应该关闭模态窗口(具体怎么关由伟胜提供方法)
			$.closeModal($("#createNewActivityPage .actions-modal"));
		}
    	 var _text = $(this).children("span");
         var _self = $(this);
         var buttons1 = [
             {
                 text: '红包领券',
                 onClick: function () {
                     _text.text("红包领券");
                     _self.siblings("p").hide();
                     createActivityPublicParam.affiliation = "1";
                 }
             },
             {
                 text: '支付宝领券页面',
                 onClick: function () {
                     _text.text("支付宝领券页面");
                     _self.siblings("p").show();
                     createActivityPublicParam.affiliation = "2";
                 }
             }
         ];
         var buttons2 = [
             {
                 text: '取消'
             }
         ];
         var groups = [buttons1, buttons2];
         $.actions(groups);
      });
    
    
    
    /**
     * 其他页面跳转
     */
    $(doc).on("click", "#createNewActivityPage .link-to-otherSetting", function() {      
            
        //跳转其他设置页面
        
        jumpOtherSettingPage();
    });
    
    
   /**
    * 是否开启口碑客切换;
    */
    $(doc).on('change', '#createNewActivityPage #checkSwitch input', function () {
      var isOpen = $(this).prop("checked"); 
      if(isOpen){ 
    	  createNewController.openKoubeiKe();
      }else{         
    	  createNewController.closeKoubeiKe();
      }
    
    });
    
    /**
     * 提交活动;
     */
    $(doc).on("click","#createNewActivityPage #submitBtn",function(){
    	if(submitFn == true){
    		submitFn = false;
    		function MyActivity() {
        		SubmitActivityData.call(this);
        	}
        	MyActivity.prototype = Object.create(SubmitActivityData.prototype);
        	MyActivity.prototype.checkParams = function () {
               var actEndDate = $("#createNewActivityPage #act-date-end").val();
        	   if(actEndDate == ""){
        		   DialogUtil.dialogWarn("请选择活动结束日期!");
        		   return false;
        	   }
        		        	  
        	   if(createActivityPublicParam.isRelativeTime == false){
        		  if(DateUtil.compareDate(createActivityPublicParam.activityStartTime,createActivityPublicParam.voucherStartTime)){
         			  DialogUtil.dialogWarn("券有效开始日期不能小于活动开始日期!");
         			  return false;
         		  }
        		  if (DateUtil.compareDate(createActivityPublicParam.activityEndTime,createActivityPublicParam.voucherEndTime)) {
        			  DialogUtil.dialogWarn("券有效结束日期不能小于活动结束日期!");
      				  return false;
      			  } 
        		  
        	   }	
	  		  
       	       if(createActivityPublicParam.activityType == ACTIVITY_TYPE.SCAN_CODE.val){
           		  if(createActivityPublicParam.affiliation==""){
           			  DialogUtil.dialogWarn("请选择二维码类型!");
           			  return false;
           		  }
               }
        	  
        	  return true;
        	};
        	MyActivity.prototype.saveData = function () {
        		createNewController.saveActivityData(); 	    
        	};
        	MyActivity.prototype.buildSubmitData = function () {
        		this.submitData = buildActivitySubmitData();
        	}; 	 
        	var myActivity = new MyActivity();
        	if(ActivityUtil.isCheckedChannel("A_PAY_CODE")==true){//收银码
        		ActivityPreloadData.queryAPayQrCodeCount(function() {
    				myActivity.send();
    			}); 	
        	}else{
        		myActivity.send();
        	}
			
    	} 
    	
    });
     
    

    $(doc).on('input','#createNewActivityPage #discountQuan input,#createNewActivityPage #df-koubeike input',function(e) {   	
    	var reg = new RegExp("^[0-9]+\.{0,1}[0-9]{0,2}$"); 	 
    	var inputVal = $(this).val();
    	var inputId = $(this).attr("id");
    	if(inputVal == ""){
    		$(this).val("");
    	}else{
    		if(!reg.test(inputVal)){
        		var indexOfPoint =inputVal.indexOf(".");
            	if(indexOfPoint != -1){
            		if(inputVal.substring(indexOfPoint+1).length>2){
            			$(this).val(inputVal.substring(0,indexOfPoint+3));
            		}
            	} 
        	}else{//通过正则过滤;
        		if(inputVal.charAt(0)=='0'&& inputVal.charAt(1)!='' && inputVal.charAt(1)!='.'){
        			$(this).val(Number(inputVal));
        		}else if(inputId == "voucherAmount" && Number(inputVal) < 1){//代金券面额只能大于等于1;
        			$(this).val(1);
        		}
        	}
          	
    	}
    	
    
	});
 
    
    
})(document, window);